<template>
  <div class="exception-template">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>异常订单处理模板</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>添加模板
        </el-button>
        <el-button type="success" @click="handleCategory">
          <el-icon><Folder /></el-icon>分类管理
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="模板名称">
          <el-input v-model="searchForm.name" placeholder="请输入模板名称" clearable />
        </el-form-item>
        <el-form-item label="异常类型">
          <el-select v-model="searchForm.type" placeholder="请选择异常类型" clearable>
            <el-option label="退款纠纷" value="refund" />
            <el-option label="服务投诉" value="complaint" />
            <el-option label="商品问题" value="product" />
            <el-option label="其他异常" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="searchForm.categoryId" placeholder="请选择分类" clearable>
            <el-option
              v-for="category in categoryList"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 模板列表 -->
    <el-card class="template-list">
      <el-table
        v-loading="loading"
        :data="templateList"
        border
        style="width: 100%"
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="name" label="模板名称" min-width="150" />
        <el-table-column prop="type" label="异常类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getExceptionTypeTag(row.type)">
              {{ getExceptionTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="分类" width="120" />
        <el-table-column prop="processType" label="处理方式" width="120">
          <template #default="{ row }">
            <el-tag :type="getProcessTypeTag(row.processType)">
              {{ getProcessTypeLabel(row.processType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="模板内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="useCount" label="使用次数" width="100" sortable />
        <el-table-column prop="createTime" label="创建时间" min-width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="success" link @click="handleCopy(row)">复制</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑模板对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加模板' : '编辑模板'"
      width="700px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="异常类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择异常类型">
            <el-option label="退款纠纷" value="refund" />
            <el-option label="服务投诉" value="complaint" />
            <el-option label="商品问题" value="product" />
            <el-option label="其他异常" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类">
            <el-option
              v-for="category in categoryList"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理方式" prop="processType">
          <el-select v-model="form.processType" placeholder="请选择处理方式">
            <el-option label="退款处理" value="refund" />
            <el-option label="补偿处理" value="compensation" />
            <el-option label="协商处理" value="negotiation" />
            <el-option label="其他处理" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="模板内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="6"
            placeholder="请输入模板内容，支持变量替换，如：{customerName}、{orderNo}等"
          />
        </el-form-item>
        <el-form-item label="变量说明" prop="variables">
          <el-input
            v-model="form.variables"
            type="textarea"
            :rows="3"
            placeholder="请输入变量说明，如：customerName-客户姓名、orderNo-订单编号等"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分类管理对话框 -->
    <el-dialog
      v-model="categoryDialogVisible"
      title="分类管理"
      width="600px"
    >
      <div class="category-header">
        <el-button type="primary" @click="handleAddCategory">
          <el-icon><Plus /></el-icon>添加分类
        </el-button>
      </div>
      <el-table
        :data="categoryList"
        border
        style="width: 100%"
      >
        <el-table-column prop="name" label="分类名称" min-width="150" />
        <el-table-column prop="templateCount" label="模板数量" width="100" />
        <el-table-column prop="createTime" label="创建时间" min-width="180" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEditCategory(row)">编辑</el-button>
            <el-button 
              type="danger" 
              link 
              :disabled="row.templateCount > 0"
              @click="handleDeleteCategory(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog
      v-model="categoryFormVisible"
      :title="categoryDialogType === 'add' ? '添加分类' : '编辑分类'"
      width="500px"
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="categoryRules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="categoryForm.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="categoryForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="categoryFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCategorySubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Folder } from '@element-plus/icons-vue'
import {
  getMerchantOrderExceptionTemplateList,
  addMerchantOrderExceptionTemplate,
  updateMerchantOrderExceptionTemplate,
  deleteMerchantOrderExceptionTemplate,
  copyMerchantOrderExceptionTemplate,
  getMerchantOrderExceptionCategoryList,
  addMerchantOrderExceptionCategory,
  updateMerchantOrderExceptionCategory,
  deleteMerchantOrderExceptionCategory
} from '@/api/merchant'

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  categoryId: ''
})

// 模板列表数据
const loading = ref(false)
const templateList = ref([])
const categoryList = ref([])

// 分页信息
const page = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  id: '',
  name: '',
  type: '',
  categoryId: '',
  processType: '',
  content: '',
  variables: '',
  remark: ''
})

// 分类对话框相关
const categoryDialogVisible = ref(false)
const categoryFormVisible = ref(false)
const categoryDialogType = ref('add')
const categoryFormRef = ref(null)
const categoryForm = reactive({
  id: '',
  name: '',
  sort: 0,
  remark: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择异常类型', trigger: 'change' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  processType: [
    { required: true, message: '请选择处理方式', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入模板内容', trigger: 'blur' },
    { min: 2, max: 1000, message: '长度在 2 到 1000 个字符', trigger: 'blur' }
  ]
}

const categoryRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ]
}

// 获取模板列表
const getTemplateList = async () => {
  loading.value = true
  try {
    const { data } = await getMerchantOrderExceptionTemplateList({
      ...searchForm,
      page: page.current,
      size: page.size
    })
    templateList.value = data.list
    page.total = data.total
  } catch (error) {
    console.error('获取模板列表失败:', error)
    ElMessage.error('获取模板列表失败')
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const getCategoryList = async () => {
  try {
    const { data } = await getMerchantOrderExceptionCategoryList()
    categoryList.value = data
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  page.current = 1
  getTemplateList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 添加模板
const handleAdd = () => {
  dialogType.value = 'add'
  Object.keys(form).forEach(key => {
    form[key] = ''
  })
  dialogVisible.value = true
}

// 编辑模板
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.keys(form).forEach(key => {
    form[key] = row[key]
  })
  dialogVisible.value = true
}

// 复制模板
const handleCopy = async (row) => {
  try {
    await copyMerchantOrderExceptionTemplate(row.id)
    ElMessage.success('复制成功')
    getTemplateList()
  } catch (error) {
    console.error('复制模板失败:', error)
  }
}

// 删除模板
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该模板吗？', '提示', {
      type: 'warning'
    })
    await deleteMerchantOrderExceptionTemplate(row.id)
    ElMessage.success('删除成功')
    getTemplateList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除模板失败:', error)
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    if (dialogType.value === 'add') {
      await addMerchantOrderExceptionTemplate(form)
      ElMessage.success('添加成功')
    } else {
      await updateMerchantOrderExceptionTemplate(form)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    getTemplateList()
  } catch (error) {
    console.error('保存模板失败:', error)
  }
}

// 打开分类管理
const handleCategory = () => {
  categoryDialogVisible.value = true
}

// 添加分类
const handleAddCategory = () => {
  categoryDialogType.value = 'add'
  Object.keys(categoryForm).forEach(key => {
    categoryForm[key] = key === 'sort' ? 0 : ''
  })
  categoryFormVisible.value = true
}

// 编辑分类
const handleEditCategory = (row) => {
  categoryDialogType.value = 'edit'
  Object.keys(categoryForm).forEach(key => {
    categoryForm[key] = row[key]
  })
  categoryFormVisible.value = true
}

// 删除分类
const handleDeleteCategory = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该分类吗？', '提示', {
      type: 'warning'
    })
    await deleteMerchantOrderExceptionCategory(row.id)
    ElMessage.success('删除成功')
    getCategoryList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除分类失败:', error)
    }
  }
}

// 提交分类表单
const handleCategorySubmit = async () => {
  if (!categoryFormRef.value) return
  
  try {
    await categoryFormRef.value.validate()
    if (categoryDialogType.value === 'add') {
      await addMerchantOrderExceptionCategory(categoryForm)
      ElMessage.success('添加成功')
    } else {
      await updateMerchantOrderExceptionCategory(categoryForm)
      ElMessage.success('更新成功')
    }
    categoryFormVisible.value = false
    getCategoryList()
  } catch (error) {
    console.error('保存分类失败:', error)
  }
}

// 获取异常类型标签类型
const getExceptionTypeTag = (type) => {
  const typeMap = {
    refund: 'danger',
    complaint: 'warning',
    product: 'error',
    other: 'info'
  }
  return typeMap[type] || ''
}

// 获取异常类型标签文本
const getExceptionTypeLabel = (type) => {
  const typeMap = {
    refund: '退款纠纷',
    complaint: '服务投诉',
    product: '商品问题',
    other: '其他异常'
  }
  return typeMap[type] || type
}

// 获取处理方式标签类型
const getProcessTypeTag = (type) => {
  const typeMap = {
    refund: 'danger',
    compensation: 'warning',
    negotiation: 'primary',
    other: 'info'
  }
  return typeMap[type] || ''
}

// 获取处理方式标签文本
const getProcessTypeLabel = (type) => {
  const typeMap = {
    refund: '退款处理',
    compensation: '补偿处理',
    negotiation: '协商处理',
    other: '其他处理'
  }
  return typeMap[type] || type
}

// 分页大小变化
const handleSizeChange = (val) => {
  page.size = val
  getTemplateList()
}

// 页码变化
const handleCurrentChange = (val) => {
  page.current = val
  getTemplateList()
}

onMounted(() => {
  getTemplateList()
  getCategoryList()
})
</script>

<style lang="scss" scoped>
.exception-template {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 500;
    }

    .header-actions {
      display: flex;
      gap: 10px;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .template-list {
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .category-header {
    margin-bottom: 20px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 